<template>
  <div>
    <div>
      <div class="cards">
        <el-button type="primary" style="margin-right: 10px" @click="handleAdd">+ 新增</el-button>
        <el-button type="warning" style="margin-right: 20px" @click="delBatch">批量删除</el-button>
        <el-select v-model="value" placeholder="请选择品类" style="width: 240px;margin-right: 10px">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-input style="width:240px;margin-right: 10px; text-align: center" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="primary" @click="rest">重 置</el-button>
      </div>
      <div class="card" style="margin-top: 10px">
        <el-table :data="data.tableData" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection"  style="border: #666666; width:10px"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="品类" prop="category"></el-table-column>
          <el-table-column label="进价(元/g)" prop="cost_price"></el-table-column>
          <el-table-column label="售价(元/g)" prop="sale_price"></el-table-column>
          <el-table-column label="规格" prop="standard"></el-table-column>
          <el-table-column label="产地" prop="production" style="label-width: 20px; size:20px"></el-table-column>
          <el-table-column label="库存量(g)" prop="store_count"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle />
              <el-button @click="handleDelete(scope.row.id)" type="danger" :icon="Delete" circle />
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-pagination
              @current-change="load"
              @size-change="load"
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              :page-sizes="[5,10,15,20]"
              background
              layout="total,sizes,prev,pager,next,jumper"
              :total="data.total"
          ></el-pagination>
        </div>
      </div>
      <!--新增-->
      <el-dialog v-model="data.formVisible" title="新增用户信息" width="500" style="margin-top:2%">
        <el-form :model="data.form" style="width: 400px; margin: 0 auto; display: flex; flex-direction: column; align-items: flex-start;">
          <!-- 设置label-width统一标签宽度 -->
          <el-form-item label="名称：" label-width="80px" style="margin-top: 20px">
            <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="品类：" label-width="80px">
            <el-input v-model="data.form.category" autocomplete="off" placeholder="请输入品类" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="进价(元/g)" label-width="80px">
            <el-input v-model="data.form.cost_price" autocomplete="off" placeholder="请输入进价(元/g)" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="售价(元/g)" label-width="80px">
            <el-input v-model="data.form.sale_price" autocomplete="off" placeholder="请输入售价(元/g)" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="规格" label-width="80px">
            <el-input v-model="data.form.standard" autocomplete="off" placeholder="请输入规格" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="产地" label-width="80px">
            <el-input v-model="data.form.production" autocomplete="off" placeholder="请输入产地" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="库存量(g)" label-width="80px">
            <el-input v-model="data.form.store_count" autocomplete="off" placeholder="请输入库存量(g)" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="状态" style="margin-left: 30px">
            <el-radio-group v-model = "data.form.status" style="width: 178px">
              <el-radio value="激活" label="激活" style="margin-left: 8px"></el-radio>
              <el-radio value="禁用" label="禁用"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述" label-width="80px">
            <el-input
                v-model="data.form.description"
                maxlength="30"
                style="width: 280px; height: 80px; resize: none; overflow-y: auto;"
                placeholder="请描述药材功能"
                show-word-limit
                type="textarea"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">保 存</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import { Search, Delete, Edit } from "@element-plus/icons-vue";
import { ref } from 'vue';
import request from '@/utils/request.js';
import { ElMessage, ElMessageBox } from "element-plus";

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  userList: [],
  formVisible: false,
  form: [],
  ids: []
});

const load = () => {
  request.get('/medicine/findAllMedicine', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      category: value.value // 新增传递品类参数
    }
  }).then(res => {
    console.log(res);
    data.tableData = res.data.content;
    data.total = res.data.page.totalElements;
  });
};

onMounted(() => {
  load();
});

// 重置
const rest = () => {
  data.name = null;
  value.value = null;
  load();
};

// 将状态值转换为布尔类型
const convertStatusToBoolean = (form) => {
  if (form.status === '激活') {
    form.status = 1;
  } else if (form.status === '禁用') {
    form.status = 0;
  }
  return form;
};

// 新增
const handleAdd = () => {
  data.formVisible = true;
  data.form = {};
};

const save = () => {
  // 先转换状态值
  data.form = convertStatusToBoolean(data.form);
  data.form.id? update() : add();
};

const add = () => {
  request.post('medicine/addMedicine', data.form).then(res => {
    if (res.code === 200) {
      data.formVisible = false;
      ElMessage.success("添加成功");
      load();
    } else {
      ElMessage.error(res.message);
    }
  });
};

// 编辑
const update = () => {
  request.put('medicine/updateMedicine', data.form).then(res => {
    if (res.code === 200) {
      data.formVisible = false;
      ElMessage.success("修改成功");
      load();
    } else {
      ElMessage.error(res.message);
    }
  });
};

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '温馨提示', { type: 'warning' }).then(() => {
    request.delete('medicine/delMedicineById/' + id).then(res => {
      console.log(res);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.message);
      }
    });
  }).catch();
};

// 编辑
const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row)); // 深拷贝
  data.formVisible = true;
};

// 多选
const handleSelectionChange = (rows) => {
  console.log(rows);
  data.ids = rows.map(row => row.id);
  console.log(data.ids);
};

// 批量删除
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据');
    return;
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '温馨提示', { type: 'warning' }).then(() => {
    request.delete('medicine/deleteBatchType', { data: data.ids }).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.message);
      }
    });
  }).catch();
};

const value = ref('');

const options = [
  {
    value: '解表类',
    label: '解表类',
  },
  {
    value: '清热类',
    label: '清热类',
  },
  {
    value: '泻下类',
    label: '泻下类',
  },
  {
    value: '祛风湿类',
    label: '祛风湿类',
  },
  {
    value: '利水渗湿类',
    label: '利水渗湿类',
  },
  {
    value: '温理类',
    label: '温理类',
  },
  {
    value: '活血化瘀类',
    label: '活血化瘀类',
  },
  {
    value: '化痰止咳平喘类',
    label: '化痰止咳平喘类',
  },
  {
    value: '补虚类',
    label: '补虚类',
  }
];
</script>

<style scoped>
.cards {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.12);
}

/* 调整表单元素的间距 */
.el-form-item {
  margin-bottom: 15px;
}

/* 可以对dialog的底部操作按钮部分进行样式微调 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>